import { _decorator, Component, Node, PolygonCollider2D, Collider2D, Contact2DType, Vec3 } from 'cc';
import { Enum_ColliderGroup } from '../Enum';
import { Player } from './Player';
const { ccclass, property } = _decorator;

@ccclass('PlayerCondroller')
export class PlayerCondroller extends Component {

    private _playerCollider: Collider2D = null;
    private _player: Player;
    public isWall: boolean = false;

    private _collisionNormal: Vec3 = new Vec3(); // 碰撞法线方向

    start() {
        this._player = this.node.parent.getComponent(Player);
        this._playerCollider = this.node.getComponent(PolygonCollider2D);
        if (this._playerCollider) {
            this._playerCollider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            this._playerCollider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
    }

    // 碰撞开始回调
    onBeginContact(self: Collider2D, other: Collider2D) {
        if (other.group === Enum_ColliderGroup.MAIN_TOWER || other.group === Enum_ColliderGroup.WALL || other.group === Enum_ColliderGroup.FENCE) {
            this.isWall = true;
            this._player.playerRadian = this._player.direction;
            console.log("碰撞时的角度：" + this._player.playerRadian );
            
            // 计算碰撞法线方向
            // Vec3.subtract(this.node.position, other.node.position, this._collisionNormal);
            // this._collisionNormal.normalize();
        }
    }

    // 碰撞结束回调
    onEndContact(self: Collider2D, other: Collider2D) {
        if (other.group === Enum_ColliderGroup.MAIN_TOWER || other.group === Enum_ColliderGroup.WALL || other.group === Enum_ColliderGroup.FENCE) {
            this.isWall = false;
            // // 计算碰撞法线方向
            // Vec3.subtract(this.node.position, other.node.position, this._collisionNormal);
            // this._collisionNormal.normalize();
        }
    }

    // 检查是否可以朝某个方向移动
    canMoveInDirection(direction: Vec3): boolean {
        if (!this.isWall) return true;

        // 计算移动方向与碰撞法线的点积
        const dot = Vec3.dot(direction, this._collisionNormal);

        // 如果点积大于0，表示方向朝向碰撞体内部，不允许移动
        // 如果点积小于0，表示方向远离碰撞体或平行，允许移动
        return dot < 0;
    }
}


